﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DefeatEpidemic.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DefeatEpidemic.API
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [GlobalActionFilter]
    public class BaseController : Controller
    {
        
    }
    public class GlobalActionFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        /// <summary>
        /// Action 执行前拦截[模型验证应该在此处先处理]
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";//解决拦截器添加后跨域不生效的问题
            string isAuth = ConfigurationHelper.GetSectionValue("authorized");
            if (isAuth == "1")
            {
                var token = context.HttpContext.Request.Headers["token"];
                Response resp = ValidateTokenJwt(token);
                if (resp.code != 1)
                {
                    context.Result = new ContentResult
                    {
                        Content = resp.message,
                        StatusCode = StatusCodes.Status200OK,
                        ContentType = "text/html;charset=utf-8"
                    };
                }
            }
        }

        public Response ValidateTokenJwt(string encryptToken)
        {
            Response resp = new Response() { code = 5000, message = "failed" };
            #region 
            string secret = Common.ConfigurationHelper.GetSectionValue("TokenSecret");
            //后续再加上后面的验证
            //解析Token，
            string json = "";
            if (!JwtHelper.DecryptToken(encryptToken, secret, out json))
            {
                resp.code = 5001;
                resp.message = "验签失败";
                return resp;
            }
            //验证载荷信息
            JwtModel jwtModel = new JwtModel();
            if (!JwtHelper.DeserializeJsonToModel(json, out jwtModel))
            {
                resp.code = 5002;
                resp.message = "序列化失败";
                return resp;
            }
            //判断Token的绝对过期时间
            if (JwtHelper.ConvertStringToDateTime(jwtModel.exp) > DateTime.Now)
            {
                resp.code = 1;
                resp.message = "success";
                return resp;
            }
            #endregion

            return resp;
        }
    }

    /// <summary>
    /// 异常拦截
    /// </summary>
    public class ExceptionFilter : IExceptionFilter
    {

        /// <summary>
        /// 发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                context.Result = new ContentResult
                {
                    Content = context.Exception.Message,//这里是把异常抛出。也可以不抛出。
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "text/html;charset=utf-8"
                };
                NLogUtil.fileLogger.Error("error:" + context.Exception.Message + ",stack:" + context.Exception.StackTrace);
            }
            context.ExceptionHandled = true;
        }

        /// <summary>
        /// 异步发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }

    }
}
